package com.zky.gulimall.order.components;

import com.rabbitmq.client.Channel;
import com.zky.gulimall.order.entity.OrderEntity;
import com.zky.gulimall.order.entity.OrderItemEntity;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @Description 消息监听, 顺序监听，消费一个再消费下一个，非并发监听
 * @Author 张开源
 * @Date 2022/12/8 11:12
 * @Version 1.0
 **/
@Component
@RabbitListener(queues = {"zky-java-queue"})
public class RabbitMqMsgListener {

    @RabbitHandler
    public void listener(Message msg, Map<String, String> map, Channel channel) throws InterruptedException {
        System.out.println("接收到的message：" + msg + "\t" + "map:" + map);
        dealAck(msg, channel);
    }

    @RabbitHandler
    public void listener(Message msg, OrderItemEntity orderItemEntity, Channel channel) throws InterruptedException {
        System.out.println("接收到的message：" + msg + "\t" + "orderItemEntity:" + orderItemEntity);
        dealAck(msg, channel);
    }

    @RabbitHandler
    public void listener(Message msg, OrderEntity orderEntity, Channel channel) throws InterruptedException {
        System.out.println("接收到的message：" + msg + "\t" + "orderEntity:" + orderEntity);
        dealAck(msg, channel);
    }

    private void dealAck(Message msg, Channel channel) {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try {
            System.out.println("deliveryTag:" + deliveryTag);
            //手动ack,false表示不是批量确认
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //有异常就拒绝，重新入队,
            //b表示是否是批量拒绝，b1表示是否要重新入队列
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
